import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		shopcar: uni.getStorageSync("shopcar") || [],
		checked: false


	},
	mutations: {
		add(state, val) {
			console.log(val);
			let flag = false;
			state.shopcar.forEach(item => {
				if (item.id == val.id) {
					item.num++;
					flag = true
				}
			})
			if (flag == false) {
				val.num = 1;
				val.status = false;
				state.shopcar.push(val)
			}
			uni.setStorageSync("shopcar", state.shopcar)
		},
		checkItem(state, id) {
			state.shopcar.forEach(item => {
				if (item.id == id) {
					item.status = !item.status
				}
			})
			//手动让数据取反
			state.checked = state.shopcar.every(item => {
				return item.status == true
			})
			//点击上面的复选框控制全选按钮



			uni.setStorageSync("shopcar", state.shopcar)


		},
		checkAll(state) {
			state.checked = !state.checked;
			// 因为在uniapp中checkbox不能用v-model 所以视图变了数据不变 我们就要手动的让数据变
			//先手动改变全选按钮的值
			state.shopcar.forEach(item => {
				item.status = state.checked
			})
			//让上面购物车数据的状态和 全选按钮状态一样
			uni.setStorageSync("shopcar", state.shopcar)
		},
		clear(state){
			state.shopcar=state.shopcar.filter(item=>{
				return item.status==false
			})
			//选中删除把不删的留下来
			state.checked=false
			uni.setStorageSync("shopcar", state.shopcar)
		},
		changeNum(state,val){
			console.log(val)
			
			uni.setStorageSync("shopcar", state.shopcar)
		}

	},
	actions: {},
	getters: {
		allPrice(state) {
			let all = 0;
			state.shopcar.forEach(item => {
				if (item.status == true) {
					all += item.num * item.retail_price
				}

			})
			return all
		}
		//计算总价
	},
});
export default store;
